<script setup lang='ts'>
import { h, defineComponent, ref, onMounted, reactive, computed } from 'vue'
import { NButton, useMessage, NCheckbox, NSwitch, NPopconfirm, zhCN, dateZhCN } from 'naive-ui'
import type { DrawerPlacement, FormInst, FormItemRule } from 'naive-ui'

import { TableStore } from '@/stores/modules/table'
import { TablecutStore } from '@/stores/modules/table-cut'
import { TableseatStore } from '@/stores/modules/table-manage'
import QrcodeVue from 'qrcode.vue'
import router from '@/router/index'
import { getTableHright } from '@/utils/autoHeight'
const { getHeight } = getTableHright(380)

const tableStore = TableStore()
const tablecutStore = TablecutStore()
const tableseatStore = TableseatStore()

const list = computed(() => tableStore.list);
let ruleForm = reactive({});
//  获取列表
onMounted(async () => {
	await getList()
	await tablecutStore.getcutList()
	await tableseatStore.getseatList()
	cutOptions.value = tablecutStore.cutList
	seatOptions.value = tableseatStore.seatList
})

//列表获取
const getList = async () => {
	return await tableStore.getList({
		page: tableStore.page - 1,
		pageSize: tableStore.pageSize,
		query: cut.value,
		query1: position.value,
		
	});
};

const cutOptions = ref()
const seatOptions = ref()
const statusOptions = ref([
	{
		label: "使用",
		value: '1',
	},
	{
		label: '空闲',
		value: '0'
	},])
const cut = ref()
const position = ref()
const state = ref()

// 搜索
const doSeacrh = async () => {
	tableStore.page = 1;
await	tableStore.getList({
		query: cut.value,
		query1: position.value,
		query2:state.value,
	})
};


// 表单验证-
const formRef = ref<FormInst>()
const message = useMessage()
const title = ref("新增桌台");

//  新建
const doAdd = (place: DrawerPlacement, row: any) => {
	Object.assign(ruleForm, { number: "", cut: "", position: "", state: "0", status: "0", time: Date.now(), _id: 0 });
	active.value = true
	wrapStyle.value = null
	qrcode.isValue = ''
}

// 提交
const submitForm = () => {
	formRef.value?.validate(async (errors) => {
		if (!errors) {
			await tableStore.SaveList(ruleForm)
			getList()
			active.value = false
		} else {
			console.log("提交失败");
		}
	})
}
// 删除
const doDelete = async (row: object) => {
	await tableStore.Delete(row._id)
	getList()
}
// 修改(编辑)
const doChangeTable = (row: any) => {
	Object.assign(ruleForm, { ...row }) // 合并
	active.value = true
	wrapStyle.value = null
	createQr(row)
}

// 新增桌号不能重复
const rules = ({
	number: [
		{ required: true, trigger: ['blur', 'input'], message: '请输入 桌号' },
		{
			required: true, trigger: ['blur'],
			validator(rule: FormItemRule, value: string) { // 验证桌号是否存在
				return new Promise<void>(async (resolve, reject) => {
					let res = await tableStore.getNumber(value)
					if (res.data.length > 0) {
						reject(Error('桌号已存在!!'))
					} else {
						resolve()
					}
				})
			},
		}],
	cut: { required: true, trigger: "blur", message: '请选择 桌型' },
	position: { required: true, trigger: "blur", message: '请选择 桌位' },
})
// 抽屉
const active = ref(false)
const placement = ref<DrawerPlacement>('right')
// 表格
const columns = [{
	title: "编号",
	key: "ids",
	align: 'center',
	render: (_: any, index: number) => {
		return `${index + 1}`
	}
},
{
	title: "桌号",
	key: "number",
	align: 'center'
},
{
	title: "桌位",
	key: "position",
	align: 'center'
},
{
	title: "桌型",
	key: "cut",
	align: 'center'
},
{
	title: "桌台状态",
	key: "state",
	render(row: any) {
		return h(NCheckbox, {
			value: row.state,
			checked: row.state == 1 ? true : false,
		});
	},
	align: 'center'
},
{
	title: "台桌启用状态",
	key: "status",
	align: 'center',
	render(row: any) {
		return h(NSwitch, {
			value: row.status,
			checked: row.status == 1 ? true : false,
		});
	},
},
{
	title: "操作",
	key: "operate",
	align: 'center',
	width: '240',
	render(row: any) {
		return [h(
			NButton, {
			ghost: true,
			strong: true,
			tertiary: true,
			type: 'primary',
			size: 'small',
			color: '#18a058',
			style: {
				padding: 6
			},
			onClick: () => CheckTable(row)
		}, {
			default: () => '查看'
		}
		),
		h(
			NButton, {
			strong: true,
			tertiary: true,
			size: 'small',
			color: '#7764ca',
			ghost: true,
			style: {
				padding: 6
			},
			onClick: () => doChangeTable(row)
		}, {
			default: () => '编辑'
		}
		),
		h(
			NPopconfirm,
			{
				onPositiveClick: () => doDelete(row),
				onNegativeClick: () => negativeClick(),
				negativeText: "取消",
				positiveText: "确定",
			},
			{
				trigger: () =>
					h(
						NButton,
						{
							strong: true,
							tertiary: true,
							size: "small",
							color: '#f00',
							ghost: true,
							style: {
								padding: 6
							},
						},
						{ default: () => "删除" }
					),
				default: () => h("span", {}, "你确定要删除吗？？？"),
			}
		),
		]
	}
},
]
const negativeClick = () => {
	active.value = false
}
// 路由跳转
const goCutTable = () => {
	router.push("/tablecut");
}
const goTable = () => {
	router.push("/tableseat");
}
// 二维码打印
const qrcode = reactive({
	isValue: ""
})
//  生成二维码
const createQr = (data: Object) => {
	if (data.number) {
		data = reactive({
			isValue: `桌号：${data.number};\n桌型：${data.cut};\n桌位：${data.position};\n桌台状态：${data.state ? '使用' : '空闲'};\n台桌启用状态：${data.status ? '已启用' : '未启用'}`
		})
	} else {
		data = reactive({
			isValue: "欢迎访问「晴天见」官网"
		})
	}
	Object.assign(qrcode, data) // 合并
}


//高度自适应
let autoTableHeight = ref(null);
const autuHeight = (height) => {
	autoTableHeight.value = window.innerHeight - height;
	window.onresize = () => {
		autoTableHeight.value = window.innerHeight - height;
	};
	return autoTableHeight.value;
}


const wrapStyle = ref(null)
// 查看 
const CheckTable = (row: any) => {
	Object.assign(ruleForm, { ...row }) // 合并
	active.value = true
	wrapStyle.value = "wap-list"
	createQr(row)
}
// 分页
const pageCount = ref(null);
// 当前页
const Pages = (page: number) => {
	tableStore.page = page;
	getList();
};
// 总页数
const PageSizes = (pageSize: number) => {
	tableStore.pageSize = pageSize;
	getList();
};
// 点击叉号搜索框失去焦点事件
const selectTable = () => {
	tableStore.getList({});
}
</script>

<template>
	<!-- 桌台查询 -->
	<n-layout>
		<n-layout-header>
			<div class="box-nav">台桌设置</div>
		</n-layout-header>
		<n-layout has-sider class="content">
			<n-layout-content style="width: 233px;">
				<div class="flex">
					<span>桌位:</span>
					<n-select class="select" :consistent-menu-width="true" placeholder="请选择桌位" clearable="true"
						@clear="selectTable" v-model:value="position" @change="seatChange" :options="seatOptions" />
				</div>
			</n-layout-content>
			<n-layout-content style="width: 233px;">
				<div class="flex">
					<span>桌型:</span>
					<n-select class="select" v-model:value="cut" clearable="true" @clear="selectTable"
						placeholder="请选择桌型" @change="cutChange" :options="cutOptions" />
				</div>
			</n-layout-content>
			<n-layout-content style="width: 279px;">
				<div class="flex">
					<span>桌台状态:</span>
					<n-select style="width: 60%;" class="select" clearable="true" @clear="selectTable"
						v-model:value="state"  :options="statusOptions" placeholder="请选择桌台状态" />
				</div>
			</n-layout-content>
			<n-button style="margin-right: 30px;" @click="doSeacrh" type="info">查询</n-button>
		</n-layout>
	</n-layout>

	<!-- 表格 -->
	<div class="sp-nav">
		<div class="number">台桌数量：{{ tableStore.total }} 件</div>
		<div>
			<n-space justify="end">
				<n-button type="primary" @click="goTable">桌位管理</n-button>
				<n-button type="warning" @click="goCutTable">桌型管理</n-button>
				<n-button type="info" @click="doAdd('right')">新建 +</n-button>
			</n-space>
		</div>
	</div>
	<n-data-table :style="{ height: `${getHeight}px` }" class="table" :max-height="autuHeight(420)" :columns="columns"
		:data="list" :pagination="pagination" :single-line="false" />

	<!-- 分页 -->
	<n-config-provider :locale="zhCN" :date-locale="dateZhCN">
		<n-space justify="end" style="margin-top: 16px;">
			<n-pagination v-model:page="tableStore.page" v-model:page-size="tableStore.pageSize"
				:page-sizes="[1, 3, 5, 7]" :page-count="pageCount" :item-count="tableStore.total" @update:page="Pages"
				@update:page-size="PageSizes" show-quick-jumper show-size-picker />
		</n-space>
	</n-config-provider>

	<!-- 抽屉- -->
	<n-drawer v-model:show="active" :width="550" :native-scrollbar="true" :placement="placement">
		<n-drawer-content :title="ruleForm._id ? (wrapStyle) ? '查看' : '修改桌台' : '新建桌台'">
			<div :class="wrapStyle"></div>
			<n-form ref="formRef" :model="ruleForm" :rules="(ruleForm._id) ? '' : rules" label-placement="left"
				label-width="auto" require-mark-placement="right-hanging" :size="size" :style="{ maxWidth: '640px' }">
				<n-form-item label="桌号" path="number">
					<n-input v-model:value="ruleForm.number" :disabled="(ruleForm._id) ? active : !active"
						placeholder="桌号" />
				</n-form-item>
				<n-form-item label="桌位" path="position">
					<n-select v-model:value="ruleForm.position" placeholder="请选择桌位" :options="seatOptions" />
				</n-form-item>
				<n-form-item label="桌型" path="cut">
					<n-select v-model:value="ruleForm.cut" placeholder="请选择桌型" :options="cutOptions" />
				</n-form-item>
				<n-form-item label="桌台状态" path="state">
					<n-radio-group v-model:value="ruleForm.state">
						<n-space>
							<n-radio value="1"> 使用</n-radio>
							<n-radio value="0"> 空闲 </n-radio>
						</n-space>
					</n-radio-group>
				</n-form-item>
				<n-form-item label="台桌启用状态" path="status">
					<n-switch v-model:value="ruleForm.status" />
				</n-form-item>
				<div style="display: inline-block; margin-left: 43px;">
					<n-button style="margin-left: 119px;margin-bottom: 10px;" type="info" @click="createQr(ruleForm)">
						生成台桌点餐二维码
					</n-button><br>
					<div class="code" v-show="qrcode.isValue">二维码只可生成一次，终身与此台桌绑定，如需更换二维码请删除桌台从新添加</div>
				</div>
				<div class="ercode">
					<div id="app" v-show="qrcode.isValue">
						<div id="printMe">
							<qrcode-vue :value="qrcode.isValue" :size="250" level="H"></qrcode-vue>
						</div>
						<n-button id="print" type="info" v-print="'#printMe'" class="print-btn">打印</n-button>
					</div>
				</div>
			</n-form>
			<template #footer>
				<div style="margin: auto;">
					<n-button type="info" @click="submitForm(formRef)">确定</n-button>
					<n-button @click="active = false">取消</n-button>
				</div>
			</template>
		</n-drawer-content>
	</n-drawer>
</template>

<style scoped>
.print-btn {
	position: absolute;
	right: 0px;
}

.wap-list {
	position: absolute;
	background-color: rgba(255, 255, 255, 0.1);
	width: 96%;
	top: 50px;
	left: 0px;
	bottom: 67px;
	z-index: 2;
}

.ercode {
	position: relative;
	margin-left: 120px;
	margin-top: 50px;
}

#print {
	margin-left: 10px;
	/* margin-bottom: 55px; */
	position: absolute;
	bottom: 6px;
}

.code {
	font-size: 12px;
	color: #999999;
}

.table {
	text-align: center;
}

.flex {
	display: flex;
}

.flex span {
	display: inline-block;
	line-height: 34px;
}

.box-nav {
	width: 100%;
	height: 45px;
	background-color: #e9eff5;
	line-height: 45px;
	padding-left: 20px;
}

.select {
	margin-left: 16px;
	width: 70%;
}

.n-button {
	margin-right: 29px;
}

.content {
	height: 90px;
	padding-top: 30px;
	border: 1px solid #fafafc;
	padding-left: 20px;
}

.sp-nav {
	margin-top: 30px;
	height: 61px;
	padding-left: 24px;
	line-height: 61px;
	background-color: #fff;
	display: flex;
	justify-content: space-between;
}

.number {
	/* padding-top: 5px; */
	color: #7764ca;
	font-weight: 600;
}
</style>
